//获取分类列表
$.ajax({
    type: 'get',
    url: '/categories',
    success: function(response) {
        var html = template('categoryTpl', { data: response });
        $('#category').html(html)
    }
});
//文章封面上传
$('#feature').on('change', function() {
    var formData = new FormData();
    formData.append('avatar', this.files[0]);
    $.ajax({
        type: 'post',
        url: '/upload',
        data: formData,
        //告诉$.ajax方法不要解析请求参数
        processData: false,
        //告诉$.ajax方法不要设置请求参数的类型
        contentType: false,
        success: function(response) {
            $('#thumbnail').val(response[0].avatar)
        }
    })
});
//添加文章
$('#addForm').on('submit', function() {
    var formData = $(this).serialize();
    $.ajax({
        type: 'post',
        url: '/posts',
        data: formData,
        success: function(response) {
            location.href = '/admin/posts.html'
        }
    })
    return false;
});
// 获取地址栏的请求参数
function getUrlParams(name) {
    var paramsAry = location.search.substr(1).split('&')
    for (var i = 0; i < paramsAry.length; i++) {
        var tmp = paramsAry[i].split('=')
        if (tmp[0] == name) {
            return tmp[1]
        }
    }
    return -1
};
//把页面修改成修改文章
if (getUrlParams('id')) {
    $.ajax({
        type: 'get',
        url: '/posts/' + getUrlParams('id'),
        success: function(response) {
            //获取分类列表
            $.ajax({
                type: 'get',
                url: '/categories',
                success: function(categories) {
                    response.categories = categories;
                    var html = template('modifyTpl', response);
                    $('#modifyBox').html(html)
                }
            });
        }
    })
}
//修改文章
$('#modifyBox').on('submit', '#modifyForm', function() {
    var formData = $(this).serialize();
    $.ajax({
        type: 'put',
        url: '/posts/' + getUrlParams('id'),
        data: formData,
        success: function() {
            location.href = '/admin/posts.html'
        }
    })
    return false;
})